<template>
	<view class="container position-relative">
		<view style="padding-bottom: 330rpx;">
			
			<view class="section-1">
				<template>
					<list-cell class="location">
						<view class="flex-fill d-flex justify-content-between align-items-center">
							<view class="store-name flex-fill">{{ store.name }}{{ table.name ? '-' + table.name : '' }}</view>
						</view>
					</list-cell>
				</template>

			</view>
			<!-- 购物车列表 begin -->
			<view class="section-2" v-if="cart.length > 0">
				<view class="cart d-flex flex-column">
					<list-cell class="location">
						<view class="flex-fill d-flex justify-content-between align-items-center">
							<view class="store-name flex-fill">未下单商品</view>
						</view>
					</list-cell>
					<list-cell last v-for="(item, index) in cart" :key="index">
						<view class="w-100 d-flex flex-column">
							<view class="d-flex align-items-center mb-10">
								<view
									class="d-flex flex-fill justify-content-between align-items-center text-color-base font-size-lg">
									<image style="width: 80rpx;height: 80rpx;" mode="aspectFill" :src="item.image">
									</image>
								</view>
								<view class="name-and-props overflow-hidden">
									<view class="text-color-base font-size-lg">{{ item.name }}</view>
								</view>
								<view
									class="d-flex flex-fill justify-content-between align-items-center text-color-base font-size-lg">
									<view>x{{ item.number }}</view>
									<view>￥{{ item.sales_price }}</view>
								</view>
							</view>
							<view class="text-truncate font-size-base text-color-assist">{{ item.props_text }}</view>
						</view>
					</list-cell>
				</view>
				
				<list-cell arrow @click="goToPackages" v-if="products.length == 0">
					<view class="flex-fill d-flex justify-content-between align-items-center">
						<view class="text-color-base">优惠券</view>
						<view v-if="coupons == 0" class="text-color-base">暂无可用</view>
						<view v-else-if="coupon.title" class="text-color-danger">
							{{ coupon.title }}(满{{ coupon.least }}减{{ coupon.value }})
						</view>
						<view v-else class="text-color-primary">可用优惠券{{ coupons }}张</view>
					</view>
				</list-cell>
				
				<list-cell last>
					<view class="flex-fill d-flex justify-content-end align-items-center">
						<view>
							总计 ￥{{ total }}
							<text v-if="coupon.value">,￥-{{ coupon.value }}</text>
							,实付
						</view>
						<view class="font-size-extra-lg font-weight-bold">￥{{ amount }}</view>
					</view>
				</list-cell>
			</view>
			<!-- 购物车列表 end -->
			
			<!-- 已下单商品 begin -->
			<view class="section-2" v-if="products.length > 0">
				<view class="cart d-flex flex-column">
					<list-cell class="location">
						<view class="flex-fill d-flex justify-content-between align-items-center">
							<view class="store-name flex-fill">已下单商品</view>
						</view>
					</list-cell>
					<list-cell last v-for="(item, index) in products" :key="index">
						<view class="w-100 d-flex flex-column">
							<view class="d-flex align-items-center mb-10">
								<view
									class="d-flex flex-fill justify-content-between align-items-center text-color-base font-size-lg">
									<image style="width: 80rpx;height: 80rpx;" mode="aspectFill" :src="item.image">
									</image>
								</view>
								<view class="name-and-props overflow-hidden">
									<view class="text-color-base font-size-lg">{{ item.title }}</view>
								</view>
								<view
									class="d-flex flex-fill justify-content-between align-items-center text-color-base font-size-lg">
									<view>x{{ item.number }}</view>
									<view>￥{{ item.price }}</view>
								</view>
							</view>
							<view class="text-truncate font-size-base text-color-assist">{{ item.spec }}</view>
						</view>
					</list-cell>
				</view>
				<list-cell arrow @click="goToPackages">
					<view class="flex-fill d-flex justify-content-between align-items-center">
						<view class="text-color-base">优惠券</view>
						<view v-if="coupons == 0" class="text-color-base">暂无可用</view>
						<view v-else-if="coupon.title" class="text-color-danger">
							{{ coupon.title }}(满{{ coupon.least }}减{{ coupon.value }})
						</view>
						<view v-else class="text-color-primary">可用优惠券{{ coupons }}张</view>
					</view>
				</list-cell>
				<list-cell last>
					<view class="flex-fill d-flex justify-content-end align-items-center">
						<view>
							总计 ￥{{ totalProducts }}
							<text v-if="coupon.value">,￥-{{ coupon.value }}</text>
							,实付
						</view>
						<view class="font-size-extra-lg font-weight-bold">￥{{ amountProducts }}</view>
					</view>
				</list-cell>
			</view>
			<!-- 已下单商品 end -->
		</view>
		<!-- 付款栏 begin -->
		<view style="z-index: 1;margin-bottom: 50rpx;"
			class="w-100 pay-box position-fixed fixed-bottom d-flex align-items-center justify-content-between bg-white">
			<view class="font-size-sm" style="margin-left: 20rpx;">合计：</view>
			<view class="font-size-lg flex-fill">￥{{ amountTotal }}</view>
			<view v-if="cart.length > 0" class="bg-warning h-100 d-flex align-items-center just-content-center text-color-white font-size-base"
				style="padding: 0 60rpx;" @tap="$u.debounce(payAfter, 500)">先下单</view>
			<view class="bg-primary h-100 d-flex align-items-center just-content-center text-color-white font-size-base"
				style="padding: 0 60rpx;" @tap="$u.debounce(submit, 500)">付款</view>
		</view>
		
		<!-- 付款栏 end -->
		<modal :show="payModalVisible" custom :mask-closable="false" :radius="'0rpx'" width="90%">
			<view class="modal-content">
				<view class="d-flex justify-content-end">
					<image src="/static/images/pay/close.png" style="width: 40rpx; height: 40rpx;"
						@tap="payModalVisible = false"></image>
				</view>
				
				<!-- 支付方式 begin -->
				<view class="payment">
					<list-cell last :hover="false"><text>支付方式</text></list-cell>
					<list-cell>
						<view class="d-flex align-items-center justify-content-between w-100 disabled"
							@click="setPayType(5)">
							<view class="iconfont iconbalance line-height-100 payment-icon"></view>
							<view class="flex-fill">余额支付（余额￥{{ member.money }}）</view>
							<view class="font-size-sm" v-if="member.money == 0">余额不足</view>
							<view class="iconfont line-height-100 checkbox checked iconradio-button-on" v-if="payType == 5">
							</view>
							<view class="iconfont line-height-100 checkbox iconradio-button-off" v-else></view>
						</view>
					</list-cell>
					<!-- <list-cell>
						<view class="d-flex align-items-center justify-content-between w-100" @click="setPayType(4)">
							<view class="iconfont-unidrink icon-alipay line-height-100 payment-icon" style="color:#07b4fd" ></view>
							<view class="flex-fill">支付宝</view>
							<view class="iconfont line-height-100 checkbox checked iconradio-button-on" v-if="payType == 4" ></view>
							<view class="iconfont line-height-100 checkbox iconradio-button-off" v-else ></view>					
						</view>
					</list-cell> -->
					<list-cell last>
						<view class="d-flex align-items-center justify-content-between w-100" @click="setPayType(3)">
							<view class="iconfont iconwxpay line-height-100 payment-icon" style="color: #7EB73A"></view>
							<view class="flex-fill">微信支付</view>
							<view class="iconfont line-height-100 checkbox checked iconradio-button-on" v-if="payType == 3">
							</view>
							<view class="iconfont line-height-100 checkbox iconradio-button-off" v-else></view>
						</view>
					</list-cell>
				</view>
				<!-- 支付方式 end -->
				
				<button type="primary" class="pay_btn" @tap="$u.debounce(pay, 500)">确认并付款</button>
			</view>
		</modal>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations,
		mapGetters
	} from 'vuex';
	import listCell from '@/components/list-cell/list-cell';
	import modal from '@/components/modal/modal';
	// #ifdef H5
	var jweixin = require('jweixin-module');
	// #endif

	export default {
		components: {
			listCell,
			modal
		},
		data() {
			return {
				cart: [], // 购物车、未下单
				products: [], // 已下单商品
				store: {},
				table: {},
				payType: 3, // 付款方式:5=余额支付,3=微信支付,4=支付宝
				coupons: 0, // 可用优惠券数量
				coupon: {} ,// 选中的
				payModalVisible: false
			};
		},
		computed: {
			...mapState(['orderType', 'address', 'member']),
			total() {
				if (!this.cart) {
					return '0.00';
				}
				return this.cart.reduce((acc, cur) => acc + cur.number * cur.sales_price, 0);
			},
			amount() {
				if (!this.cart) {
					return '0.00';
				}
				let amount = this.cart.reduce((acc, cur) => acc + cur.number * cur.sales_price, 0);
				if (this.products.length > 0) {
					return amount.toFixed(2);
				}
				// 减去优惠券
				if (this.coupon.hasOwnProperty('id')) {
					amount -= parseFloat(this.coupon.value);
				}
				return amount.toFixed(2);
			},
			totalProducts() {
				if (!this.products) {
					return '0.00';
				}
				return this.products.reduce((acc, cur) => acc + cur.number * cur.price, 0);
			},
			amountProducts() {
				if (!this.products) {
					return '0.00';
				}
				let amount = this.products.reduce((acc, cur) => acc + cur.number * cur.price, 0);
				// 减去优惠券
				if (this.coupon.hasOwnProperty('id')) {
					amount -= parseFloat(this.coupon.value);
				}
				return amount.toFixed(2);
			},
			amountTotal() {
				let amount = 0;
				if (this.cart) {
					amount += this.cart.reduce((acc, cur) => acc + cur.number * cur.sales_price, 0);
				}
				if (this.products) {
					amount += this.products.reduce((acc, cur) => acc + cur.number * cur.price, 0);
				}
				// 减去优惠券
				if (this.coupon.hasOwnProperty('id')) {
					amount -= parseFloat(this.coupon.value);
				}
				return amount.toFixed(2);
			}
		},
		onShow() {
			this.init();
			
		},
		onPullDownRefresh() {
			this.init();
		},
		onHide() {
			this.coupons = 0;
		},
		onLoad() {
			
		},
		methods: {
			...mapMutations(['SET_ORDER_TYPE', 'SET_MEMBER']),
			...mapGetters(['isLogin']),
			init() {
				this.cart = uni.getStorageSync('cart');
				this.table = uni.getStorageSync('table');
				this.store = uni.getStorageSync('store');
				
				this.getCoupons();
				
				this.loadOrders();
				
				let paytype = uni.getStorageSync('paytype');
				this.payType = paytype ? paytype : 3;
				
				uni.stopPullDownRefresh();
			},
			// 更改支付方式
			setPayType(paytype) {
				this.payType = 0;
				this.payType = paytype;
				uni.setStorage({
					key: 'paytype',
					data: paytype
				})
			},
			async getCoupons() {
				//0=通用,1=自取,2=外卖
				let type = this.orderType == 'takein' ? 1 : 2;
				let data = await this.$u.api.couponCount({
					shop_id: this.store.id,
					type: type
				});
				if (data) {
					this.coupons = data;
				}
			},
			// 加载已下单的商品
			async loadOrders() {
				let table = await this.$u.api.shopTable({
					id: this.table?.id,
					shop_id: this.store?.id
				});
				if (table) {
					this.$store.commit('SET_TABLE', table);
					
					this.products = table.products;
				}
			},
			goToPackages() {
				let amount = this.amountTotal;
				let coupon_id = this.coupon.id ? this.coupon.id : 0;
				let type = this.orderType == 'takein' ? 1 : 2;
				let shop_id = this.store.id;
				uni.navigateTo({
					url: '/pages/components/pages/packages/index?amount=' + amount + '&coupon_id=' + coupon_id +
						'&shop_id=' + shop_id + '&type=' + type
				});
			},
			submit() {
				this.payModalVisible = true;
			},
			async payAfter() {
				let that = this;
				
				uni.showLoading({
					title: '加载中'
				});
				
				let data = {
					type: this.orderType == 'takeout' ? 2 : 1, // 购买类型:1=自取,2=外卖
					address_id: 0, // 外卖配送地址
					shop_id: this.store.id, // 店铺id
					mobile: '', // 联系电话
					gettime: 0, // 取餐时间
					pay_type: this.payType, // 支付类型
					remark: '', // 备注
					product_id: [],
					spec: [],
					number: [],
					coupon_id: 0, // 优惠券id
					table_id: this.table.id ? this.table.id : 0
				};
				
				this.cart.forEach((item, index) => {
					let spec = item.props_text.replace(/,/g, '|');
					if (!spec) {
						// 占位
						spec = '-1';
					}
					data.product_id.push(item.id);
					data.spec.push(spec);
					data.number.push(item.number);
				});
				
				//console.log(data);
				let order = await this.$u.api.orderPayAfter(data);
				if (!order) {
					uni.hideLoading();
					this.$api.msg('下单失败');
					return;
				}
				uni.removeStorageSync('cart');
				this.init();
			},
			async pay() {
				let that = this;
				
				uni.showLoading({
					title: '加载中'
				});

				let data = {
					type: this.orderType == 'takeout' ? 2 : 1, // 购买类型:1=自取,2=外卖
					address_id: 0, // 外卖配送地址
					shop_id: this.store.id, // 店铺id
					mobile: '', // 联系电话
					gettime: 0, // 取餐时间
					pay_type: this.payType, // 支付类型
					remark: '', // 备注
					product_id: [],
					spec: [],
					number: [],
					coupon_id: this.coupon.id ? this.coupon.id : 0, // 优惠券id
					table_id: this.table.id ? this.table.id : 0
				};

				this.cart.forEach((item, index) => {
					let spec = item.props_text.replace(/,/g, '|');
					if (!spec) {
						// 占位
						spec = '-1';
					}
					data.product_id.push(item.id);
					data.spec.push(spec);
					data.number.push(item.number);
				});

				//console.log(data);
				let order = await this.$u.api.orderPayAfter(data);
				if (!order) {
					uni.hideLoading();
					return;
				}

				if (this.payType == 3) {
					// 微信支付
					this.weixinPay(order);
				} else if (this.payType == 5) {
					// 余额支付
					this.balancePay(order);
				} else if (this.payType == 4) {
					// 支付宝支付
					this.aliPay(order);
				}
				uni.hideLoading()
				return
			},
			async balancePay(order) {
				let pay = await this.$u.api.payBalance({
					out_trade_no: order.out_trade_no
				});

				uni.hideLoading();
				if (!pay) {
					return;
				}

				this.member.money -= this.amount
				this.$store.commit('SET_MEMBER', this.member);
				uni.removeStorageSync('cart');
				uni.removeStorageSync('store');
				uni.removeStorageSync('table');
				this.$store.commit('SET_TABLE', {
					id: this.table.id,
					name: this.table.name,
					shop_id: this.table.shop_id,
					switch: this.table.switch,
					products: []
				});
				uni.switchTab({
					url: '/pages/take-foods/take-foods',
					fail(res) {
						console.log(res);
					}
				});
			},
			async weixinPay(order) {
				let that = this;
				let data = await this.$u.api.payUnify({
					out_trade_no: order.out_trade_no
				});
				if (!data) {
					uni.hideLoading();
					return;
				}
				if (data.trade_type == 'MWEB') {
					// #ifdef H5
					// 微信外的H5
					location.href = data.mweb_url;
					// #endif
				} else if (data.trade_type == 'JSAPI') {
					// #ifdef H5
					// 微信内的H5
					let config = await this.$u.api.payJssdkBuildConfig();
					if (config) {

						jweixin.config(config);
						jweixin.ready(function() {
							jweixin.chooseWXPay({
								timestamp: data
									.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
								nonceStr: data.nonce_str, // 支付签名随机串，不长于 32 位
								package: 'prepay_id=' + data
									.prepay_id, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
								signType: 'MD5', // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
								paySign: data.paySign, // 支付签名
								success: function(res) {
									// 支付成功后的回调函数

									uni.removeStorageSync('cart');
									uni.switchTab({
										url: '/pages/take-foods/take-foods'
									});
								},
								fail: function(err) {
									//console.log('fail:' + JSON.stringify(err));
									//that.$api.msg('fail:' + JSON.stringify(err))
									that.$api.msg('支付失败');
								}
							});
						});
						jweixin.error(function(res) {
							//that.$api.msg(JSON.stringify(res));
							that.$api.msg('支付失败');
						});
					} else {
						that.$api.msg('支付失败');
					}
					// #endif

					// #ifdef MP-WEIXIN
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: data.timeStamp,
						nonceStr: data.nonce_str,
						package: 'prepay_id=' + data.prepay_id,
						signType: 'MD5',
						paySign: data.paySign,
						success: function(res) {

							uni.removeStorageSync('cart');
							uni.removeStorageSync('store');
							uni.removeStorageSync('table');
							that.$store.commit('SET_TABLE', {
								id: that.table.id,
								name: that.table.name,
								shop_id: that.table.shop_id,
								switch: that.table.switch,
								products: []
							});
							uni.switchTab({
								url: '/pages/take-foods/take-foods'
							});
						},
						fail: function(err) {
							//console.log('fail:' + JSON.stringify(err));
							//that.$api.msg('fail:' + JSON.stringify(err))
							that.$u.toast('支付失败');
						}
					});
					// #endif
				} else if (data.trade_type == 'APP') {
					//console.log('app支付');
					//console.log(data);
					//App端，微信支付 orderInfo 为 Object 类型。
					uni.requestPayment({
						provider: 'wxpay',
						orderInfo: data.orderInfo,
						success(res) {
							//console.log('支付成功');
							//console.log(res);

							uni.removeStorageSync('cart');
							uni.switchTab({
								url: '/pages/take-foods/take-foods'
							});
						},
						fail(res) {
							//console.log('支付失败');
							//console.log(res)
							that.$api.msg('支付失败');
						}
					});
				}
			},
			async alipay() {

				// #ifdef H5
				window.open(this.$unishow + '/pay/alipay?order_id=' + this.orderId);

				setTimeout(function() {
					uni.showModal({
						title: '提示',
						content: '是否已支付?',
						cancelText: '否',
						confirmText: '是',
						success: function(res) {
							if (res.confirm) {

								uni.removeStorageSync('cart');
								uni.switchTab({
									url: '/pages/take-foods/take-foods'
								});
							} else if (res.cancel) {
								//console.log('用户点击取消');
							}
						},
						fail: function(res) {
							//console.log(res)
						}
					});
				}, 3000);
				// #endif

				// #ifdef APP-PLUS
				let orderInfo = await this.$u.api.payAlipay({
					order_id: this.orderId
				});
				if (orderInfo) {
					//console.log(orderInfo);
					uni.requestPayment({
						provider: 'alipay',
						orderInfo: orderInfo,
						success: function(res) {
							console.log('success:' + JSON.stringify(res));

							uni.removeStorageSync('cart');
							uni.switchTab({
								url: '/pages/take-foods/take-foods'
							});
						},
						fail: function(err) {
							console.log('fail:' + JSON.stringify(err));
							that.$api.msg('支付失败');
						}
					});
				}

				// #endif

			}
		}
	};
</script>

<style lang="scss" scoped>
	.container {
		padding: 30rpx;
	}

	.arrow {
		width: 50rpx;
		height: 50rpx;
		position: relative;
		margin-right: -10rpx;
	}

	.location {
		.store-name {
			font-size: $font-size-lg;
		}

		.iconfont {
			font-size: 50rpx;
			line-height: 100%;
			color: $color-primary;
		}
	}

	.section-1 {
		margin-bottom: 30rpx;

		.contact {
			.contact-tip {
				margin-left: 10rpx;
				border: 2rpx solid $color-primary;
				padding: 6rpx 10rpx;
				color: $color-primary;
			}
		}
	}

	.section-2 {
		margin-bottom: 30rpx;
		.name-and-props {
			width: 65%;
		}
	}

	.payment {
		margin-bottom: 30rpx;

		.disabled {
			color: $text-color-grey;
		}

		.payment-icon {
			font-size: 44rpx;
			margin-right: 10rpx;
		}

		.checkbox {
			font-size: 36rpx;
			margin-left: 10rpx;
		}

		.checked {
			color: $color-primary;
		}
	}

	.pay-box {
		box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1);
		height: 100rpx;
	}

	.modal-content {
		.change-address-btn {
			line-height: 2;
			padding: 0 1em;
		}

		.pay_btn {
			width: 100%;
			border-radius: 50rem !important;
			line-height: 3;
		}
	}

	.choice {
		background-color: $bg-color-grey;
		border-radius: 38rpx;
		display: flex;
		align-items: center;
		font-size: $font-size-sm;
		padding: 0 38rpx;
		color: $text-color-assist;

		.dinein,
		.takeout {
			width: 50%;
			position: relative;
			display: flex;
			align-items: center;

			&.active {
				padding: 14rpx 38rpx;
				color: #ffffff;
				background-color: $color-primary;
				border-radius: 38rpx;
			}
		}

		.takeout {
			margin-left: 20rpx;
			height: 100%;
			flex: 1;
			padding: 14rpx 0;
		}

		.dinein.active {
			//margin-left: -38rpx;
		}

		.takeout.active {
			//margin-right: -38rpx;
		}
	}
</style>
